package com.xgkj.diyiketang.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xgkj.diyiketang.ProtocolConst;
import com.xgkj.diyiketang.activity.SearchShangJiaActivity;
import com.xgkj.diyiketang.activity.SellerDetailActivity;
import com.xgkj.diyiketang.activity.data.MiShiAdapter;
import com.xgkj.diyiketang.activity.data.ShangQuanAdapter;
import com.xgkj.diyiketang.data.FoodInfo;
import com.xgkj.diyiketang.data.SellerInfo;
import com.xgkj.diyiketang.data.ShangQuanInfo;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.http.engine.TaskEventListener;
import com.xgkj.diyiketang.task.FoodListTask;
import com.xgkj.diyiketang.task.MiShiListOrDetailTask;
import com.xgkj.diyiketang.task.ShangQuanListTask;
import com.xgkj.diyiketang.util.EatShowSetting;
import com.xgkj.diyiketang.util.PopupHelper;
import com.xgkj.diyiketang.weidget.PullToRefreshListView;
import com.xgkj.diyiketang.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by XCKJ_Paladowow on 2016/5/23.
 */
public class Fragment_MiShi extends BaseFragment implements PullToRefreshListView.OnRefreshListener, PullToRefreshListView.OnLoadDataListener, View.OnClickListener {
    private Context mContext;
    private int currentPage_c = 1;
    private int currentPage_w = 1;
    private int size = 10;
    private PullToRefreshListView chiboListView;
    private PullToRefreshListView wangyouListView;
    private CheckBox mChiboCheck;
    private CheckBox mWangYouCheck;
    private MiShiAdapter mAdapter;
    private MiShiAdapter wAdapter;
    private int chiboTaskId = -1;
    private int wangyouTaskId = -1;
    private TextView mLocation;
    private PopupHelper mPopupHelper;
    private ShangQuanAdapter sAdapter;
    private int didianTaskId = -1;
    private ShangQuanInfo sqInfo;
    private String mLocalString;
    private TextView back;
    private String mAreaId;
    private ImageView sousuo;
    private int getfoodlistTaskId = -1;
    private String areaid;

    @Override
    protected int getContentViewId() {
        return 0;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mishi, null);
        mContext = getActivity();
        initView(view);
        return view;
    }


    private void initView(View view) {
//        back = (TextView) view.findViewById(R.id.back);
//        back.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                finish();
//            }
//        });
        mLocalString = EatShowSetting.getInstance(mContext).getLocal();
        sousuo = (ImageView) view.findViewById(R.id.shangjia_search);
        sousuo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(mContext, SearchShangJiaActivity.class));
            }
        });
        mLocation = (TextView) view.findViewById(R.id.didian);
        mLocation.setText(mLocalString);
        mLocation.setOnClickListener(this);
        mChiboCheck = (CheckBox) view.findViewById(R.id.chiborenzheng_btn);
        mChiboCheck.setOnClickListener(this);
        mWangYouCheck = (CheckBox) view.findViewById(R.id.wangyoutuijian_btn);
        mWangYouCheck.setOnClickListener(this);
        mChiboCheck.setChecked(true);
        mWangYouCheck.setChecked(false);

        chiboListView = (PullToRefreshListView) view.findViewById(R.id.chiborenzheng_list);
        wangyouListView = (PullToRefreshListView) view.findViewById(R.id.wangyoutuijian_list);
        chiboListView.setVisibility(View.VISIBLE);
        wangyouListView.setVisibility(View.GONE);

        chiboListView.init(mContext, true);
        mAdapter = new MiShiAdapter(mContext);
        chiboListView.setAdapter(mAdapter, true);
        chiboListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (chiboListView.getHeaderViewsCount() > 0) {
                    position--;
                }
                if (position < 0 || position >= mAdapter.getCount()) return;
                SellerInfo fdinfo = (SellerInfo) mAdapter.getItem(position);
                String fdid = fdinfo.getBusinessId();
                Intent intent = new Intent(mContext, SellerDetailActivity.class);
                intent.putExtra("BSUINESSID", fdid);
                startActivity(intent);
            }
        });
        chiboListView.setOnRefreshListener(this);
        chiboListView.setOnLoadDataListener(this);
        chiboListView.doRefresh();


        wangyouListView.init(mContext, true);
        wAdapter = new MiShiAdapter(mContext);
        wangyouListView.setAdapter(wAdapter, true);
        wangyouListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (wangyouListView.getHeaderViewsCount() > 0) {
                    position--;
                }
                if (position < 0 || position >= wAdapter.getCount()) return;
                SellerInfo fdinfo = (SellerInfo) wAdapter.getItem(position);
                String fdid = fdinfo.getBusinessId();
                Intent intent = new Intent(mContext, SellerDetailActivity.class);
                intent.putExtra("BSUINESSID", fdid);
                startActivity(intent);
            }
        });
        wangyouListView.setOnRefreshListener(this);
        wangyouListView.setOnLoadDataListener(this);
        wangyouListView.doRefresh();

        sAdapter = new ShangQuanAdapter(mContext);
        //  getChiboList("");
        getfoodList();

    }

    private void initPopWindow() {
        mPopupHelper = new PopupHelper(mContext, sAdapter);
        mPopupHelper.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                mPopupHelper.dismissDropDownView();
                sqInfo = (ShangQuanInfo) sAdapter.getItem(position);
                if (sqInfo != null) {
                    String dd = sqInfo.getTradingAreaName();
                    mLocation.setText(dd);
                    if (dd.equals(mLocalString)) {
                        mAreaId = "";
                    } else {
                        mAreaId = sqInfo.getTradingAreaId();
                    }

                    if (chiboListView.getVisibility() == View.VISIBLE) {
                        currentPage_c = 1;
                        getChiboList(mAreaId);
                    } else if (wangyouListView.getVisibility() == View.VISIBLE) {
                        currentPage_w = 1;
                        getWangYouList(mAreaId);
                    }

                }
            }
        });

        mPopupHelper.setOnDisMissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                //popLayout.setVisibility(View.GONE);
            }
        });

        mPopupHelper.setOnCancleListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mPopupHelper.dismissDropDownView();
            }
        });
    }

    private void getDiDian() {
        ShangQuanListTask sqTask = new ShangQuanListTask(mLocalString);
        sqTask.addListener(new MishiListner(mContext));
        didianTaskId = getEatShowApp().getTaskManager().addTask(sqTask);
    }

    private void getChiboList(String areaid) {

        if (chiboTaskId != -1) {
            return;
        }

        if (currentPage_c == 0) {
            chiboListView.setNoNextPage();
            return;
        }

        MiShiListOrDetailTask task = new MiShiListOrDetailTask(size, currentPage_c, mLocalString, "0", areaid);
        task.addListener(new MishiListner(mContext));
        chiboTaskId = getEatShowApp().getTaskManager().addTask(task);

    }

    private void getfoodList() {

        FoodListTask ftask = new FoodListTask(10, 1, mLocalString);
        ftask.addListener(new MishiListner(mContext));
        getfoodlistTaskId = getEatShowApp().getTaskManager().addTask(ftask);
    }

    private void getWangYouList(String areaid) {

        if (wangyouTaskId != -1) {
            return;
        }
        if (currentPage_w == 0) {
            wangyouListView.setNoNextPage();
            return;
        }

        MiShiListOrDetailTask task = new MiShiListOrDetailTask(size, currentPage_w, mLocalString, "1", areaid);
        task.addListener(new MishiListner(mContext));
        wangyouTaskId = getEatShowApp().getTaskManager().addTask(task);
    }

    class MishiListner extends ShowToastTaskEventListener {
        public MishiListner(Context context) {
            super(context);
        }

        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
            if (taskId == chiboTaskId) {
                chiboTaskId = -1;

                if (currentPage_c == 1) {
                    mAdapter.clearData();
                    chiboListView.onRefreshComplete();
                    chiboListView.enableLoadMore();
                } else {
                    chiboListView.onLoadDataComplete(true);
                }
                List<SellerInfo> fansList = new ArrayList<SellerInfo>();
                if (data != null) {
                    fansList = (List<SellerInfo>) data;
                }

                if (fansList != null && fansList.size() > 0) {
                    mAdapter.updateData(fansList);

                }
                /// getfoodList();
                // mAreaId="";
                currentPage_c = result;


            } else if (taskId == wangyouTaskId) {
                wangyouTaskId = -1;
                // sAdapter.clearData();
                if (currentPage_w == 1) {
                    wAdapter.clearData();
                    wangyouListView.onRefreshComplete();
                    wangyouListView.enableLoadMore();
                } else {
                    wangyouListView.onLoadDataComplete(true);
                }
                List<SellerInfo> fansList = new ArrayList<SellerInfo>();
                if (data != null) {
                    fansList = (List<SellerInfo>) data;
                }

                if (fansList != null && fansList.size() > 0) {
                    wAdapter.updateData(fansList);

                }
                //getfoodList();
                //mAreaId="";
                currentPage_w = result;


            } else if (taskId == didianTaskId) {
                List<ShangQuanInfo> sqList = new ArrayList<ShangQuanInfo>();
                if (data != null) {
                    sqList = (List<ShangQuanInfo>) data;
                }

                if (sqList != null && sqList.size() > 0) {
                    ShangQuanInfo sqinfo = new ShangQuanInfo();
                    sqinfo.setTradingAreaName(mLocalString);
                    sqList.add(0, sqinfo);
                    sAdapter.updateData(sqList);
                }
                initPopWindow();
                mPopupHelper.showDropDownView(mLocation);
            } else if (taskId == getfoodlistTaskId) {
                if (data != null) {

                    if (chiboListView.getVisibility() == View.VISIBLE) {

                        List<FoodInfo> mfoodlist = new ArrayList<FoodInfo>();
                        int pageCount = 0;
                        int currentPage = 0;
                        int nextPage = 0;

                        JSONObject jsonString = (JSONObject) data;
                        currentPage = jsonString.getIntValue(ProtocolConst.CURRENT_PAGE);
                        pageCount = jsonString.getIntValue(ProtocolConst.PAGE_COUNT);
                        nextPage = currentPage >= pageCount ? 0 : (currentPage + 1);
                        areaid = jsonString.getString("areaId");
                        mAdapter.setAreaId(areaid);
                        mfoodlist = JSON.parseArray(jsonString.getString(ProtocolConst.LIST_TAG), FoodInfo.class);
                        mAdapter.addFoodList(mfoodlist);
                        getChiboList("");
                    } else if (wangyouListView.getVisibility() == View.VISIBLE) {
                        List<FoodInfo> mfoodlist = new ArrayList<FoodInfo>();
                        int pageCount = 0;
                        int currentPage = 0;
                        int nextPage = 0;

                        JSONObject jsonString = (JSONObject) data;
                        currentPage = jsonString.getIntValue(ProtocolConst.CURRENT_PAGE);
                        pageCount = jsonString.getIntValue(ProtocolConst.PAGE_COUNT);
                        nextPage = currentPage >= pageCount ? 0 : (currentPage + 1);
                        areaid = jsonString.getString("areaId");
                        wAdapter.setAreaId(areaid);
                        mfoodlist = JSON.parseArray(jsonString.getString(ProtocolConst.LIST_TAG), FoodInfo.class);
                        wAdapter.addFoodList(mfoodlist);
                        getWangYouList("");
                    }


                }

            }
        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
            if (taskId == chiboTaskId) {
                chiboTaskId = -1;
                if (currentPage_c == 1) {
                    chiboListView.onRefreshComplete();
                } else {
                    chiboListView.onLoadDataComplete(false);
                }
            } else if (taskId == wangyouTaskId) {
                wangyouTaskId = -1;
                if (currentPage_w == 1) {
                    wangyouListView.onRefreshComplete();
                } else {
                    wangyouListView.onLoadDataComplete(false);
                }
            }
        }

        @Override
        public void handleTaskMessage(int taskId, Object data) {
            super.handleTaskMessage(taskId, data);
        }
    };

    @Override
    public void onPullRefresh() {

    }

    @Override
    public void onLoadMore() {
        if (chiboListView.getVisibility() == View.VISIBLE) {
            if (mAreaId == null) {
                getChiboList("");
            } else {
                getChiboList(mAreaId);
            }

        } else if (wangyouListView.getVisibility() == View.VISIBLE) {
            if (mAreaId == null) {
                getWangYouList("");
            } else {
                getWangYouList(mAreaId);
            }

        }
    }

    @Override
    public void onRefresh() {
        if (chiboListView.getVisibility() == View.VISIBLE) {
            currentPage_c = 1;
            if (mAreaId == null) {
                getChiboList("");
            } else {
                getChiboList(mAreaId);
            }

        } else if (wangyouListView.getVisibility() == View.VISIBLE) {
            currentPage_w = 1;
            if (mAreaId == null) {
                getWangYouList("");
            } else {
                getWangYouList(mAreaId);
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.chiborenzheng_btn:
                mChiboCheck.setChecked(true);
                mWangYouCheck.setChecked(false);
                chiboListView.setVisibility(View.VISIBLE);
                wangyouListView.setVisibility(View.GONE);
                //mLocation.setText(mLocalString);
                //mAreaId="";
                sAdapter.clearData();
                mAdapter.clearData();
//                if (mAdapter != null && mAdapter.getCount() == 1) {
                //getChiboList("");
                getfoodList();
                currentPage_c = 1;
                getChiboList(mAreaId);
//                }
                break;

            case R.id.wangyoutuijian_btn:
                mWangYouCheck.setChecked(true);
                mChiboCheck.setChecked(false);
                wangyouListView.setVisibility(View.VISIBLE);
                chiboListView.setVisibility(View.GONE);
                //mLocation.setText(mLocalString);
                //mAreaId="";
                sAdapter.clearData();
                wAdapter.clearData();
//                if (wAdapter != null && wAdapter.getCount() == 1) {
                //getWangYouList("");

                getfoodList();
                currentPage_w = 1;
                getWangYouList(mAreaId);
//                }
                break;
            case R.id.didian:
                sAdapter.clearData();
                getDiDian();
                break;
        }

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        mLocalString = EatShowSetting.getInstance(mContext).getLocal();
        mLocation.setText(mLocalString);
        if(wangyouListView.getVisibility() == View.VISIBLE){
            wAdapter.addFoodList(new ArrayList<FoodInfo>());
            EatShowSetting.getInstance(mContext).setLocal(mLocalString);
            currentPage_w = 1;
            getfoodList();
//            getWangYouList("");
        }else if(chiboListView.getVisibility() == View.VISIBLE){
            mAdapter.addFoodList(new ArrayList<FoodInfo>());
            EatShowSetting.getInstance(mContext).setLocal(mLocalString);
            currentPage_c = 1;
            getfoodList();
//            getChiboList("");
        }


    }
}
